package com.sinosoft.cloud.access.abc.listener;

import com.sinosoft.cloud.access.transformer.TransListener;
import com.sinosoft.utility.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.*;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * cloud-access
 *
 * @title: cloud-access
 * @package: com.sinosoft.cloud.access.abc.listener
 * @author: yangming
 * @date: 2017/11/23 下午1:57
 */
@Component
public class AbcTransListener implements TransListener {

    protected static final Log logger = LogFactory.getLog(AbcTransListener.class);


    @Override
    public void beforeTransEvent(String msg) {

    }

    /**
     * 替换节点名
     * @param msg
     */
    @Override
    public String afterTransEvent(String msg) {

        /**
         * 报文很短 就不会是打印节点报文
         */
        if(msg !=null && msg.length()<1000){
            return msg;
        }
        Document document = getDomByXml(msg);
        if (document != null) {
            renameNode(document, "//Prnts/C", "Prnt");
            renameNode(document, "//Messages/C", "Prnt");
            msg = document.asXML();
        }
        return msg;
    }


    private static Document getDomByXml(String xml) {

        Document document = null;

        try {
            document = DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.exceptionToString(e));
        }
        return document;
    }

    /**
     * 根据xpath 获取节点 批量改名
     *
     * @param doc
     * @param strXpath
     * @param rename
     */
    private static void renameNode(Document doc, String strXpath, String rename) {
        XPath typeXpath = doc.createXPath(strXpath);
        List<? extends Node> nodes = typeXpath.selectNodes(doc);

        int index = 0;
        for (Node node : nodes) {
            index++;
            node.setName(rename + index);
        }

        if (logger.isDebugEnabled()) {
            logger.debug(doc.asXML());
        }
    }
}
